package com.topvision.myviewtest.rxjava.rxtest;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SeekBar;

import com.bumptech.glide.Glide;
import com.topvision.myviewtest.R;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

public class RxTestActivity extends AppCompatActivity {

    @BindView(R.id.id_picture)
    ImageView mIdPicture;
    @BindView(R.id.id_seekbar)
    SeekBar mIdSeekbar;
    @BindView(R.id.activity_rx_test)
    LinearLayout mActivityRxTest;

    private int curProgress;
    private Bitmap mBitmap;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_rx_test);
        ButterKnife.bind(this);

        mBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.rx_test_picture);
        Glide.with(this).load(R.drawable.rx_test_picture).into(mIdPicture);

        mIdSeekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                curProgress = progress;
                doBlur();
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });


    }

    private void doBlur() {
        Observable.create(new ObservableOnSubscribe<Bitmap>() {
            @Override
            public void subscribe(ObservableEmitter<Bitmap> e) throws Exception {
                Bitmap blurBitmap = BlurBitmapUtils.blurBitmap(RxTestActivity.this, mBitmap, curProgress == 0 ? 1 : curProgress);
                if (blurBitmap != null) {
                    e.onNext(blurBitmap);
                    e.onComplete();
                }
            }
        }).subscribeOn(Schedulers.newThread()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<Bitmap>() {
            @Override
            public void accept(Bitmap bitmap) throws Exception {
                mIdPicture.setImageBitmap(bitmap);
            }
        });
    }
}
